#coding: utf-8

import numpy as np
from PIL import Image


def img2binimg(img, threshold:int=200, resize=None):
    '''图片转二进制图像'''
    if isinstance(img, str):
        img = Image.open(img)    
    img = img.convert('L')
    if resize is not None:
        img = img.resize(resize, Image.ANTIALIAS)
    bin_map_table = []
    for i in range(256):
        if i < threshold:
            bin_map_table.append(0)
        else:
            bin_map_table.append(1)
    img = img.point(bin_map_table, '1')
    return img


def img2bindata(img, threshold:int=200, resize=None):
    '''图片转二进制数据'''
    if isinstance(img, str):
        img = Image.open(img)
    img = img2binimg(img, threshold, resize)
    pix_data = img.load()
    w = img.size[0]
    h = img.size[1] // 8
    data = np.zeros((h, w), dtype=np.uint8)
    for y in range(h):
        for x in range(w):
            d = 0
            for i in range(8):
                d  = d << 0
                if pix_data[x, y*8+i]:
                    d |= 1 << i
            data[y, x] = d
    return data


if __name__ == '__main__':
    img2bindata('test.jpg', resize=(128, 64))